<template>
  <div
    ref="componentRef" 
    :data-component-id="component.id"
    :class="[
        'rendered-component', 
        { 'selected': designStore.selectedComponentId === component.id }, 
        { 'container-indicator-border': isContainer(component.type) && designStore.selectedComponentId !== component.id },
        { 'is-dragging-self': isBeingDragged },
        { 'drag-over-container': isContainer(component.type) && isDragOverContainer },
    ]"
    :style="effectiveComponentStyle"
    @mousedown="handleMouseDown"
    @click="handleClick"
    @contextmenu.prevent="showContextMenu"
    @dragover.prevent="handleContainerDragOver"
    @drop.stop="handleContainerDrop"
    @dragleave="handleContainerDragLeave"
  >
    <!-- 添加拖动手柄区域 - 所有选中的组件都显示拖动手柄 -->
    <div 
      v-if="designStore.selectedComponentId === component.id"
      class="drag-handle"
      @mousedown.stop="handleDragHandleMouseDown"
      title="拖动区域 - 点击此处拖动组件"
    >
      <span class="drag-handle-text">拖动</span>
    </div>
    
    <!-- 表格组件特殊处理 -->
    <template v-if="component.type === 'el-table'">
      <el-table
        v-bind="filteredProps"
        :data="component.props?.data || []"
        style="width: 100%; height: 100%;"
      >
        <el-table-column
          v-for="(column, index) in component.props?.columns || []"
          :key="index"
          :prop="column.prop"
          :label="column.label"
          :width="column.width"
          :align="column.align || 'center'"
          :fixed="column.fixed"
          :sortable="column.sortable"
        />
      </el-table>
    </template>
    
    <!-- 组件库组件特殊处理 -->
    <template v-else-if="isLibraryComponent">
      <component
        :is="resolvedComponent"
        v-if="resolvedComponent"
        v-bind="adaptedProps"
      >
        <!-- 递归渲染子组件 -->
        <template v-if="(isContainer(component.type) || isGroupComponent) && component.children && component.children.length > 0">
          <DynamicRenderer
            v-for="child in component.children"
            :key="child.id" 
            :component="child"
          />
        </template>
      </component>
    </template>
    
    <!-- 其他类型组件的渲染 -->
    <component
      v-else
      :is="resolvedComponent"
      v-if="resolvedComponent"
      v-bind="filteredProps"
      :label="isOptionComponent ? labelValue : undefined"
      :modelValue="isGroupComponent || component.type === 'el-select' ? modelValue : undefined"
      @update:modelValue="handleModelValueUpdate"
    >
      <!-- 渲染el-select的选项 -->
      <template v-if="component.type === 'el-select' && component.props?.options">
        <el-option
          v-for="option in component.props.options"
          :key="typeof option === 'string' ? option : option.value"
          :label="typeof option === 'string' ? option : option.label"
          :value="typeof option === 'string' ? option : option.value"
        />
      </template>
      
      <!-- Pass children recursively -->
      <template v-else-if="(isContainer(component.type) || isGroupComponent) && component.children && component.children.length > 0">
        <DynamicRenderer
          v-for="child in component.children"
          :key="child.id" 
          :component="child"
        />
      </template>
      <!-- Render default slot content for non-containers/non-groups (like button, span) 
           or for individual radio/checkbox options if they have textContent -->
      <template v-else>
        {{ component.props?.buttonText || component.props?.textContent || '' }}
      </template>
    </component>

  </div>

  <div 
    v-if="isContextMenuVisible" 
    class="context-menu"
    :style="contextMenuPosition" 
    @click.stop
  >
    <div class="context-menu-item" @click="handleBringToFront">置于顶层</div>
    <div class="context-menu-item" @click="handleSendToBack">置于底层</div>
  </div>
</template>

<script setup lang="ts">
import { defineProps, resolveComponent, getCurrentInstance, defineAsyncComponent, nextTick, ref, computed, watch, onUnmounted, type CSSProperties } from 'vue';
import { useDesignStore, type CanvasComponent, isContainerType } from '../stores/designStore';
import { v4 as uuidv4 } from 'uuid';
import { cloneDeep, throttle } from 'lodash-es';
import { adaptPropsForLibraryComponent } from '../utils/componentAdapter';

const parsePx = (value: string | undefined | number): number => {
  if (typeof value === 'number') return value;
  if (typeof value === 'string' && value.endsWith('px')) {
    const parsed = parseFloat(value.slice(0, -2));
    return isNaN(parsed) ? 0 : parsed;
  }
  return 0; 
};

const DynamicRenderer = defineAsyncComponent(() => import('./DynamicRenderer.vue'));

const props = defineProps<{ component: CanvasComponent }>();
const designStore: ReturnType<typeof useDesignStore> = useDesignStore();
const instance = getCurrentInstance();

const componentRef = ref<HTMLElement | null>(null);
const isBeingDragged = ref(false);

// 鼠标拖动相关状态
const isMouseDown = ref(false);
const dragStartX = ref(0);
const dragStartY = ref(0);
const dragStartLeft = ref(0);
const dragStartTop = ref(0);
// 记录鼠标在组件内的相对位置（抓取点）
const grabOffsetX = ref(0);
const grabOffsetY = ref(0);
// 缓存拖动过程中的关键信息，避免重复查询DOM
const dragCache = ref<{
  parentRect?: DOMRect;
  canvasRect?: DOMRect;
  canvasWidth?: number;
  canvasHeight?: number;
  componentWidth?: number;
  componentHeight?: number;
  initialParentId: string | null;
  finalTargetParentId?: string | null;
  finalTargetStyle?: CSSProperties;
  hoveredContainerId?: string | null;
  hoveredContainerRect?: DOMRect;
  lastParentId?: string | null; // 记录上一次的父容器ID，用于检测变化
  initialAbsolutePosition?: { left: number; top: number }; // 组件在开始拖动时的绝对位置
  mouseStartX?: number;  // 开始拖动时的鼠标X坐标
  mouseStartY?: number;  // 开始拖动时的鼠标Y坐标
} | null>(null);

const isContextMenuVisible = ref(false);
const contextMenuPosition = ref({ top: '0px', left: '0px' });
const contextTargetComponentId = ref<string | null>(null);
const isDragOverContainer = ref(false);

const isDraggable = computed(() => {
    return props.component.type !== 'el-radio' && props.component.type !== 'el-checkbox';
});

const showContextMenu = (event: MouseEvent) => {
    if(designStore.selectedComponentId !== props.component.id) {
        designStore.selectComponent(props.component.id);
    }

    contextTargetComponentId.value = props.component.id;
    contextMenuPosition.value = {
        top: `${event.clientY}px`,
        left: `${event.clientX}px`,
    };
    isContextMenuVisible.value = true;
    document.addEventListener('click', closeContextMenuOnClickOutside, { once: true, capture: true });
};

const closeContextMenuOnClickOutside = (event: MouseEvent) => {
    const contextMenuEl = instance?.vnode?.el?.querySelector('.context-menu');
    if (contextMenuEl && contextMenuEl.contains(event.target as Node)) {
         document.addEventListener('click', closeContextMenuOnClickOutside, { once: true, capture: true });
         return; 
    }
    isContextMenuVisible.value = false;
    contextTargetComponentId.value = null; 
};

const handleBringToFront = () => {
    if (contextTargetComponentId.value) {
        designStore.bringToFront(contextTargetComponentId.value);
    }
    isContextMenuVisible.value = false;
};

const handleSendToBack = () => {
    if (contextTargetComponentId.value) {
        designStore.sendToBack(contextTargetComponentId.value);
    }
    isContextMenuVisible.value = false;
};

onUnmounted(() => {
    document.removeEventListener('click', closeContextMenuOnClickOutside, { capture: true });
    cleanupMouseListeners();
});

const filteredProps = computed(() => {
  const { 
    textContent,
    buttonText,
    modelValue,
    label,
    ...rest 
  } = props.component.props || {};
  return rest;
});

const isGroupComponent = computed(() => {
    return props.component.type === 'el-radio-group' || props.component.type === 'el-checkbox-group';
});

const isOptionComponent = computed(() => {
    return props.component.type === 'el-radio' || props.component.type === 'el-checkbox';
});

const modelValue = computed(() => {
    if (props.component.type === 'el-select') {
        // 对于el-select组件，如果没有设置modelValue，
        // 则返回第一个选项的值作为默认值
        if (props.component.props?.modelValue !== undefined) {
            return props.component.props.modelValue;
        }
        const options = props.component.props?.options || [];
        if (options.length > 0) {
            const firstOption = options[0];
            return typeof firstOption === 'string' ? firstOption : firstOption.value;
        }
        return '';
    }
    return props.component.props?.modelValue;
});

const labelValue = computed(() => {
    return props.component.props?.label;
});

const resolvedComponent = computed(() => {
  if (!props.component?.type) return null;
  try {
    const resolved = resolveComponent(props.component.type);
    if (typeof resolved === 'object' && resolved !== null) {
        return resolved;
    } else {
        console.warn(`[DynamicRenderer] Failed to resolve component type '${props.component.type}'. It resolved to:`, resolved, '. Rendering as div.');
        return 'div';
    }
  } catch (error) {
    console.error(`[DynamicRenderer] Error resolving component type '${props.component.type}':`, error);
    return 'div';
  }
});

const handleModelValueUpdate = (newValue: any) => {
    console.log(`[DynamicRenderer] ${props.component.id} @update:modelValue received:`, newValue); 
    if (isGroupComponent.value || props.component.type === 'el-select') {
        designStore.updateComponentProps(props.component.id, { modelValue: newValue });
    }
};

// 添加本地辅助函数来获取组件绝对位置
const getComponentAbsolutePosition = (componentId: string): { left: number; top: number } | null => {
  // 此函数逻辑与CanvasArea中的getComponentAbsolutePosition相同
  const component = designStore.findComponentById(designStore.canvasComponents, componentId);
  if (!component) {
    return null;
  }

  const componentLeft = parsePx(component.style?.left);
  const componentTop = parsePx(component.style?.top);

  const parent = designStore.findParentComponent(designStore.canvasComponents, componentId);
  if (!parent) {
    // 根组件
    return { left: componentLeft, top: componentTop };
  } else {
    // 嵌套组件，递归计算
    const parentPosition = getComponentAbsolutePosition(parent.id);
    if (parentPosition) {
      return { 
        left: parentPosition.left + componentLeft,
        top: parentPosition.top + componentTop 
      };
    } else {
      return null;
    }
  }
};

// 判断组件类型是否为交互式组件
const isInteractiveComponent = computed(() => {
  const interactiveTypes = [
    'el-button', 
    'button',
    'el-input', 
    'el-radio', 
    'el-checkbox', 
    'el-select', 
    'el-switch',
    'el-slider',
    'el-color-picker',
    'el-date-picker',
    'el-time-picker',
    'el-rate',
    'el-table'
  ];
  // 增加调试输出，确认组件类型
  console.log(`[DynamicRenderer] 检查组件类型: ${props.component.type}, 是否交互式: ${interactiveTypes.includes(props.component.type)}`);
  return interactiveTypes.includes(props.component.type);
});

// 更新交互元素选择器，包含更多Element Plus组件的内部元素
const interactiveSelector = `
  input, button, select, textarea, a,
  .el-radio__inner, .el-checkbox__inner, .el-radio__label, .el-checkbox__label,
  .el-button, .el-input__inner, .el-input__suffix, .el-input__prefix,
  .el-switch__core, .el-slider__button, .el-color-picker__trigger,
  .el-select__caret, .el-select-dropdown__item,
  .el-date-editor, .el-date-picker__header-label, .el-picker-panel__icon-btn,
  .el-time-panel, .el-rate__item, .el-pagination__sizes, .el-pagination__jump,
  .el-table__row, .el-table__header
`;

// 专用的拖动手柄处理函数
const handleDragHandleMouseDown = (event: MouseEvent) => {
  event.preventDefault();
  event.stopPropagation();
  
  console.log(`[DynamicRenderer handleDragHandleMouseDown] Starting drag from handle for: ${props.component.id}`);
  // 启动拖动逻辑
  isMouseDown.value = true;
  isBeingDragged.value = true;
  designStore.setDraggingState(true);

  // 获取当前父容器
  const parent = designStore.findParentComponent(designStore.canvasComponents, props.component.id);
  const parentId = parent ? parent.id : null;
  
  // 初始化拖动缓存
  dragCache.value = {
    initialParentId: parentId,
    lastParentId: parentId,
    mouseStartX: event.clientX,
    mouseStartY: event.clientY
  };
  
  // 记录组件初始位置（相对于其容器）
  const style = props.component.style || {};
  dragStartLeft.value = parsePx(style.left as string);
  dragStartTop.value = parsePx(style.top as string);
  
  // 记录鼠标在组件内的相对位置（抓取点）
  if (componentRef.value) {
    const rect = componentRef.value.getBoundingClientRect();
    grabOffsetX.value = event.clientX - rect.left;
    grabOffsetY.value = event.clientY - rect.top;
    
    // 记录组件尺寸
    dragCache.value.componentWidth = rect.width;
    dragCache.value.componentHeight = rect.height;
  }
  
  // 获取画布信息
  const canvasContent = document.querySelector('.canvas-content') as HTMLElement;
  if (canvasContent) {
    dragCache.value = {
      ...dragCache.value,
      canvasRect: canvasContent.getBoundingClientRect(),
      canvasWidth: canvasContent.scrollWidth,
      canvasHeight: canvasContent.scrollHeight,
    };
  }
  
  // 添加全局鼠标事件监听器
  document.addEventListener('mousemove', throttledMouseMove);
  document.addEventListener('mouseup', handleMouseUp);
  
  // 如果组件未被选中，则选中它
  if (designStore.selectedComponentId !== props.component.id) {
    designStore.selectComponent(props.component.id);
  }
};

const handleMouseDown = (event: MouseEvent) => {
  // 检查点击来源是否为调整手柄
  const targetElement = event.target as HTMLElement;
  if (targetElement && targetElement.classList.contains('resize-handle')) {
    console.log(`[DynamicRenderer handleMouseDown] Mouse down on resize handle - ignoring for drag.`);
    return;
  }
  
  // 检查组件是否可拖动
  if (!isDraggable.value) {
    console.log(`[DynamicRenderer handleMouseDown] Component not draggable: ${props.component.id} (${props.component.type})`);
    return;
  }

  // 如果是交互式组件并点击的不是拖动手柄，则优先使用原生交互行为
  if (isInteractiveComponent.value) {
    if (targetElement.classList.contains('drag-handle')) {
      // 如果点击的是拖动手柄，则在handleDragHandleMouseDown中处理
      return;
    }
    
    // 如果点击的是交互元素，则允许原生行为
    if (componentRef.value && targetElement.closest(interactiveSelector) && componentRef.value.contains(targetElement)) {
      console.log(`[DynamicRenderer handleMouseDown] Clicked on interactive element within ${props.component.id}. Allowing native behavior.`);
      
      // 选择组件但不开始拖动
      if (designStore.selectedComponentId !== props.component.id) {
        designStore.selectComponent(props.component.id);
      }
      return;
    }
  } else {
    // 非交互式组件的处理逻辑
    // 检查点击目标是否是组件内部的一个交互元素
    if (componentRef.value && targetElement.closest(interactiveSelector) && componentRef.value.contains(targetElement)) {
      console.log(`[DynamicRenderer handleMouseDown] Clicked on interactive element within ${props.component.id}. Allowing native behavior.`);
      return;
    }
  }
  
  // 开始拖动
  console.log(`[DynamicRenderer handleMouseDown] Starting drag for component: ${props.component.id}`);
  isMouseDown.value = true;
  isBeingDragged.value = true;
  designStore.setDraggingState(true);

  // 获取当前父容器
  const parent = designStore.findParentComponent(designStore.canvasComponents, props.component.id);
  const parentId = parent ? parent.id : null;
  
  // 初始化拖动缓存
  dragCache.value = {
    initialParentId: parentId,
    lastParentId: parentId,
    mouseStartX: event.clientX,
    mouseStartY: event.clientY
  };
  
  // 记录组件初始位置（相对于其容器）
  const style = props.component.style || {};
  dragStartLeft.value = parsePx(style.left as string);
  dragStartTop.value = parsePx(style.top as string);
  
  // 记录鼠标在组件内的相对位置（抓取点）
  if (componentRef.value) {
    const rect = componentRef.value.getBoundingClientRect();
    grabOffsetX.value = event.clientX - rect.left;
    grabOffsetY.value = event.clientY - rect.top;
    
    // 记录组件尺寸
    dragCache.value.componentWidth = rect.width;
    dragCache.value.componentHeight = rect.height;
  }
  
  // 获取画布信息 - 更新以捕获完整的画布尺寸
  const canvasContent = document.querySelector('.canvas-content') as HTMLElement;
  if (canvasContent) {
    dragCache.value = {
      ...dragCache.value,
      canvasRect: canvasContent.getBoundingClientRect(),
      canvasWidth: canvasContent.scrollWidth,  // 使用scrollWidth捕获实际宽度
      canvasHeight: canvasContent.scrollHeight, // 使用scrollHeight捕获实际高度
    };
  }
  
  // 添加全局鼠标事件监听器
  document.addEventListener('mousemove', throttledMouseMove);
  document.addEventListener('mouseup', handleMouseUp);
  
  // 阻止默认行为和冒泡
  event.preventDefault();
  event.stopPropagation();
  
  // 如果组件未被选中，则选中它
  if (designStore.selectedComponentId !== props.component.id) {
    designStore.selectComponent(props.component.id);
  }
};

// 使用节流函数限制mousemove事件处理频率，提高性能
const handleMouseMoveImpl = (event: MouseEvent) => {
  if (!isMouseDown.value || !dragCache.value) return;

  // 当前鼠标位置
  const mouseX = event.clientX;
  const mouseY = event.clientY;
  
  // 获取画布元素
  const canvasContent = document.querySelector('.canvas-content') as HTMLElement;
  if (!canvasContent) return;
  
  // 获取画布的位置和大小（包括滚动和可见区域）
  const canvasRect = canvasContent.getBoundingClientRect();
  const canvasScrollLeft = canvasContent.scrollLeft;
  const canvasScrollTop = canvasContent.scrollTop;
  const totalCanvasWidth = canvasContent.scrollWidth;
  const totalCanvasHeight = canvasContent.scrollHeight;
  const visibleCanvasWidth = canvasRect.width;
  const visibleCanvasHeight = canvasRect.height;
  
  // 首先重置所有容器的悬停状态
  document.querySelectorAll('.drag-over-container').forEach(el => 
    el.classList.remove('drag-over-container')
  );
  
  // 获取组件尺寸信息用于边界检查
  const componentWidth = dragCache.value.componentWidth || 100;
  const componentHeight = dragCache.value.componentHeight || 32;
  
  // 标记是否找到有效容器
  let foundValidContainer = false;
  let targetContainer: HTMLElement | null = null;
  let targetContainerId: string | null = null;
  let containerRect: DOMRect | null = null;
  
  // 遍历所有可能的容器组件进行检测
  const containers = document.querySelectorAll('.rendered-component');
  for (const container of Array.from(containers)) {
    // 跳过当前正在拖动的组件
    if ((container as HTMLElement).dataset.componentId === props.component.id) {
      continue;
    }
    
    const rect = container.getBoundingClientRect();
    // 使用更严格的安全边距，确保鼠标明确在容器内部
    const safeMargin = Math.min(10, rect.width * 0.1);
    
    if (
      mouseX >= rect.left + safeMargin && 
      mouseX <= rect.right - safeMargin && 
      mouseY >= rect.top + safeMargin && 
      mouseY <= rect.bottom - safeMargin
    ) {
      const containerId = (container as HTMLElement).dataset.componentId;
      if (containerId) {
        const containerComponent = designStore.findComponentById(
          designStore.canvasComponents, 
          containerId
        );
        
        // 确认它是一个容器类型的组件且不是自己的子组件(避免循环嵌套)
        if (
          containerComponent && 
          isContainer(containerComponent.type) && 
          !isDescendantOfComponent(containerId, props.component.id)
        ) {
          targetContainer = container as HTMLElement;
          targetContainerId = containerId;
          containerRect = rect;
          foundValidContainer = true;
          
          // 添加视觉指示
          targetContainer.classList.add('drag-over-container');
          break;
        }
      }
    }
  }
  
  // 根据是否找到有效容器来决定使用哪种坐标系
  let finalStyle: CSSProperties = {};
  const gridSize = designStore.gridSize;
  
  // 确定最终目标父容器ID
  const finalParentId = foundValidContainer ? targetContainerId : null;
  
  // 分支1: 在有效容器内 - 使用容器相对坐标系
  if (foundValidContainer && targetContainer && containerRect && targetContainerId) {
    // 计算相对于容器左上角的位置，考虑抓取点偏移
    let relativeX = mouseX - containerRect.left - grabOffsetX.value;
    let relativeY = mouseY - containerRect.top - grabOffsetY.value;
    
    // 网格对齐
    const snappedX = Math.round(relativeX / gridSize) * gridSize;
    const snappedY = Math.round(relativeY / gridSize) * gridSize;
    
    // 确保不超出容器边界
    const maxContainerX = Math.max(0, containerRect.width - componentWidth);
    const maxContainerY = Math.max(0, containerRect.height - componentHeight);
    
    finalStyle = {
      left: `${Math.max(0, Math.min(maxContainerX, snappedX))}px`,
      top: `${Math.max(0, Math.min(maxContainerY, snappedY))}px`
    };
    
    console.log(`[DragMove] 有效容器: 鼠标(${mouseX},${mouseY}), 容器左上角(${containerRect.left},${containerRect.top}), 相对位置(${snappedX},${snappedY}), 最终位置(${finalStyle.left},${finalStyle.top})`);
  } 
  // 分支2: 不在有效容器内 - 使用画布绝对坐标系
  else {
    // 计算相对于画布的位置，考虑抓取点偏移
    let canvasX = mouseX - canvasRect.left - grabOffsetX.value + canvasScrollLeft;
    let canvasY = mouseY - canvasRect.top - grabOffsetY.value + canvasScrollTop;
    
    // 网格对齐
    const snappedX = Math.round(canvasX / gridSize) * gridSize;
    const snappedY = Math.round(canvasY / gridSize) * gridSize;
    
    // 确保组件不会超出画布边界，考虑组件尺寸
    const maxCanvasX = Math.max(0, totalCanvasWidth - componentWidth);
    const maxCanvasY = Math.max(0, totalCanvasHeight - componentHeight);
    
    // 考虑滚动区域和可见区域
    const effectiveMaxX = Math.max(0, Math.min(maxCanvasX, visibleCanvasWidth + canvasScrollLeft - componentWidth));
    const effectiveMaxY = Math.max(0, Math.min(maxCanvasY, visibleCanvasHeight + canvasScrollTop - componentHeight));
    
    finalStyle = {
      left: `${Math.max(0, Math.min(effectiveMaxX, snappedX))}px`,
      top: `${Math.max(0, Math.min(effectiveMaxY, snappedY))}px`
    };
    
    console.log(`[DragMove] 画布: 鼠标(${mouseX},${mouseY}), 画布左上角(${canvasRect.left},${canvasRect.top}), 画布尺寸(${visibleCanvasWidth}x${visibleCanvasHeight}), 滚动(${canvasScrollLeft},${canvasScrollTop}), 相对位置(${snappedX},${snappedY}), 边界(${effectiveMaxX},${effectiveMaxY}), 最终位置(${finalStyle.left},${finalStyle.top})`);
  }
  
  // 统一应用样式更新
  designStore.updateComponentStyle(props.component.id, finalStyle);
  
  // 记录父容器变化
  if (dragCache.value && dragCache.value.lastParentId !== finalParentId) {
    console.log(`[DragMove] 父容器变化: ${dragCache.value.lastParentId || '画布'} → ${finalParentId || '画布'}`);
  }
  
  // 更新缓存中的目标信息
  if (dragCache.value) {
    dragCache.value.finalTargetParentId = finalParentId;
    dragCache.value.finalTargetStyle = finalStyle;
    dragCache.value.lastParentId = finalParentId;
  }
};

// 使用节流函数来限制鼠标移动事件的处理频率
const throttledMouseMove = throttle(handleMouseMoveImpl, 16); // 约60fps

const handleMouseUp = (event: MouseEvent) => {
  if (!isMouseDown.value) return;
  
  console.log(`[DynamicRenderer handleMouseUp] Ending drag for component: ${props.component.id}`);
  
  // 清除所有容器的悬停指示
  document.querySelectorAll('.drag-over-container').forEach(el => {
    el.classList.remove('drag-over-container');
  });
  
  // 检查是否需要更新组件的父子关系
  if (dragCache.value && dragCache.value.finalTargetParentId !== undefined && 
      dragCache.value.finalTargetStyle && 
      dragCache.value.initialParentId !== dragCache.value.finalTargetParentId) {
    // 如果父容器发生了变化，调用moveComponent更新DOM结构
    console.log(`[DynamicRenderer handleMouseUp] Changing parent from ${dragCache.value.initialParentId} to ${dragCache.value.finalTargetParentId}`);
    designStore.moveComponent(
      props.component.id, 
      dragCache.value.finalTargetParentId, 
      dragCache.value.finalTargetStyle
    );
  }
  
  // 重置状态
  isMouseDown.value = false;
  isBeingDragged.value = false;
  designStore.setDraggingState(false);
  dragCache.value = null;
  
  // 清理全局鼠标事件监听器
  cleanupMouseListeners();
};

const cleanupMouseListeners = () => {
  document.removeEventListener('mousemove', throttledMouseMove);
  document.removeEventListener('mouseup', handleMouseUp);
};

const handleClick = (event: MouseEvent) => {
  // 如果组件正在被拖动，则不处理点击事件
  if (isBeingDragged.value) {
    console.log(`[DynamicRenderer handleClick] Component being dragged, ignoring click.`);
    event.stopPropagation();
    return;
  }
  
  // 始终优先选中组件
  if (designStore.selectedComponentId !== props.component.id) {
    console.log(`[DynamicRenderer handleClick] Selecting component: ${props.component.id}`);
    designStore.selectComponent(props.component.id);
    event.preventDefault(); // 阻止原生行为
    event.stopPropagation();
    return;
  }
  
  const target = event.target as HTMLElement;
  const componentElement = componentRef.value;
  
  // 定义交互元素的 CSS 选择器
  const interactiveSelector = 'input, button, select, textarea, .el-radio__inner, .el-checkbox__inner, .el-radio__label, .el-checkbox__label';

  // 默认阻止交互元素的原生行为
  console.log(`[DynamicRenderer handleClick] Preventing native behavior for: ${props.component.id}`);
  event.preventDefault();
  
  // 阻止事件冒泡到父级 DynamicRenderer 或 CanvasArea，防止它们取消选中
  event.stopPropagation(); 
};

// 保留HTML5拖放API用于组件容器的放置处理
const handleContainerDragOver = (event: DragEvent) => {
    if (!isContainer(props.component.type)) return;
    if (designStore.isDraggingComponent && designStore.selectedComponentId === props.component.id) return;

    event.preventDefault();
    if (event.dataTransfer) {
        event.dataTransfer.dropEffect = event.dataTransfer.effectAllowed === 'copy' ? 'copy' : 'move';
    }
    
    // 设置拖拽悬停状态，显示视觉提示
    isDragOverContainer.value = true;
};

const handleContainerDrop = (event: DragEvent) => {
    // 只处理容器类型的实例
    if (!isContainer(props.component.type)) return;

    event.preventDefault();
    event.stopPropagation(); // 防止画布处理此放置事件

    const dragDataString = event.dataTransfer?.getData('application/json');
    if (!dragDataString) return;

    let dragData: any;
    try {
        dragData = JSON.parse(dragDataString);
    } catch (error) {
        console.error("[Container Drop] Failed to parse dragData:", error);
        designStore.setDraggingState(false);
        return;
    }

    // 只有移动操作才检查是否放置到自身
    if (dragData.action === 'move' && dragData.id === props.component.id) {
        console.log(`[Container ${props.component.id}] Drop ignored: trying to drop component ${dragData.id} onto itself.`);
        designStore.setDraggingState(false); // 仍然需要重置拖动状态
        return;
    }
    
    // 如果到达这里，则是有效的放置目标
    console.log(`[Container ${props.component.id}] Drop Detected! Processing action: ${dragData.action}`);

    try {
        const containerRect = (event.currentTarget as HTMLElement).getBoundingClientRect();
        const currentGridSize = designStore.gridSize;

        // 检查放置位置是否真的在容器内部，考虑边界情况
        const isInside = (
            event.clientX >= containerRect.left && 
            event.clientX <= containerRect.right && 
            event.clientY >= containerRect.top && 
            event.clientY <= containerRect.bottom
        );

        // 如果不在容器内部，则让画布处理此放置
        if (!isInside) {
            console.log(`[Container ${props.component.id}] Drop position outside container bounds, redirecting to canvas.`);
            // 延迟将组件添加到根画布，让当前函数结束后进行
            setTimeout(() => {
                // 重新触发drop事件到画布
                const canvasContentEl = document.querySelector('.canvas-content');
                if (canvasContentEl) {
                    const newDropEvent = new DragEvent('drop', {
                        clientX: event.clientX,
                        clientY: event.clientY,
                        dataTransfer: event.dataTransfer
                    });
                    canvasContentEl.dispatchEvent(newDropEvent);
                }
            }, 10);
            designStore.setDraggingState(false);
            return;
        }

        const dropXRelative = event.clientX - containerRect.left;
        const dropYRelative = event.clientY - containerRect.top;

        let targetRelativeX: number;
        let targetRelativeY: number;

        if (dragData.action === 'add') {
            targetRelativeX = dropXRelative;
            targetRelativeY = dropYRelative;
        } else if (dragData.action === 'move') {
            const offsetX = dragData.offsetX ?? 0;
            const offsetY = dragData.offsetY ?? 0;
            targetRelativeX = dropXRelative - offsetX;
            targetRelativeY = dropYRelative - offsetY;
        } else {
            console.error("[Container Drop] Unknown drag action:", dragData.action);
            return;
        }

        const snappedRelativeX = Math.round(targetRelativeX / currentGridSize) * currentGridSize;
        const snappedRelativeY = Math.round(targetRelativeY / currentGridSize) * currentGridSize;

        if (isNaN(snappedRelativeX) || isNaN(snappedRelativeY)) {
             console.error("[Container Drop] Relative coordinate calculation resulted in NaN!", { targetRelativeX, targetRelativeY });
             designStore.setDraggingState(false);
             return;
        }

        const finalRelativeStyle = {
            left: `${snappedRelativeX}px`,
            top: `${snappedRelativeY}px`,
        };
        console.log(`[Container ${props.component.id}] Calculated final RELATIVE style:`, finalRelativeStyle);

        const targetContainerId = props.component.id;

        if (dragData.action === 'add') {
            const newComponentBase: Partial<CanvasComponent> = {
                type: dragData.type,
                props: { ...(dragData.defaultProps || {}) },
                style: finalRelativeStyle,
                children: (isContainerType(dragData.type)) ? [] : undefined
            };
            console.log(`[Container ${props.component.id}] Calling addComponent with RELATIVE style.`);
            designStore.addComponent(newComponentBase as CanvasComponent, targetContainerId);
        } else if (dragData.action === 'move') {
            console.log(`[Container ${props.component.id}] Calling moveComponent for ${dragData.id} with RELATIVE style.`);
            designStore.moveComponent(dragData.id, targetContainerId, finalRelativeStyle);
        }

    } catch (error) {
        console.error("[Container Drop] Error processing drop:", error);
    } finally {
        // 无论成功还是失败，都清理拖拽状态
        isDragOverContainer.value = false;
        designStore.setDraggingState(false);
    }
};

const handleContainerDragLeave = (event: DragEvent) => {
    // 当拖拽离开容器时，移除视觉提示
    isDragOverContainer.value = false;
};

watch(() => props.component, (newVal, oldVal) => {
  // console.log(`[DynamicRenderer] Component prop updated for ID ${newVal.id}:`, newVal);
}, { deep: true });

watch(() => props.component.style, (newStyle, oldStyle) => {
    console.log(`[DynamicRenderer Watcher ${props.component.id}] Style changed:`, 
                { 
                    oldWidth: oldStyle?.width, newWidth: newStyle?.width, 
                    oldHeight: oldStyle?.height, newHeight: newStyle?.height 
                });
}, { deep: true });

const isContainer = (type: string): boolean => {
    return ['div', 'el-row', 'el-radio-group', 'el-checkbox-group', 'el-table'].includes(type);
};

/**
 * 处理将组件拖放到接收区域上的事件
 */
const handleDropOnDropZone = (event: DragEvent, containerId: string | null = null) => {
  event.preventDefault();
  event.stopPropagation();
  
  try {
    // 清除拖放状态
    designStore.setDraggingState(false);
    
    // 解析拖拽的数据
    const dragData = event.dataTransfer?.getData('application/json');
    if (!dragData) {
      console.error('[DynamicRenderer] No drag data found');
      return;
    }

    const parsedData = JSON.parse(dragData);
    
    // 确保parentId是string类型或null
    const parentId = containerId === '' ? null : containerId;
    
    // 计算位置（这里需要根据实际情况添加代码）
    let left = 0;
    let top = 0;
    
    // 日志输出最终坐标和父容器信息
    console.log(`[DropZone] Final coordinates: left=${left}, top=${top}, parentId=${parentId}`);
    
    // 处理新组件或现有组件的移动
    if (parsedData.isNew) {
      // 添加新组件
      const newComponent: Partial<CanvasComponent> = {
        type: parsedData.componentType,
        style: {
          position: 'absolute',
          left: `${left}px`,
          top: `${top}px`,
          zIndex: 1,
        }
      };
      designStore.addComponent(newComponent as CanvasComponent, parentId);
    } else {
      // 移动现有组件
      designStore.moveComponent(parsedData.componentId, parentId, {
        left: `${left}px`,
        top: `${top}px`
      });
    }
    
  } catch (error) {
    console.error('[DynamicRenderer] Error handling drop:', error);
  }
};

// 添加本地辅助函数来检查组件是否是另一个组件的后代
const isDescendantOfComponent = (descendantId: string, ancestorId: string): boolean => {
  const components = designStore.canvasComponents;
  return checkIsDescendant(components, descendantId, ancestorId);
};

// 递归检查后代关系的辅助函数
const checkIsDescendant = (components: CanvasComponent[], descendantId: string, ancestorId: string): boolean => {
  const descendant = designStore.findComponentById(components, descendantId);
  if (!descendant) return false;
  
  let current = descendant;
  let parent = designStore.findParentComponent(components, current.id);
  
  while (parent) {
    if (parent.id === ancestorId) {
      return true;
    }
    current = parent;
    parent = designStore.findParentComponent(components, current.id);
  }
  
  return false;
};

// 添加新的计算属性来增强样式处理
const effectiveComponentStyle = computed(() => {
  // 先从组件自身获取样式信息
  const baseStyle = props.component.style || {};
  
  // 确保所有关键样式属性存在，特别是用于直接控制元素尺寸的属性
  const result = { ...baseStyle };
  
  // 确保需要的样式属性有设置，如果没有则使用默认值
  if (!result.width) result.width = 'auto';
  if (!result.height) result.height = 'auto';
  
  // 显式添加position属性以确保组件相对于其父容器定位
  if (!result.position) result.position = 'absolute';
  
  return result;
});

// 判断是否是组件库组件
const isLibraryComponent = computed(() => {
  return props.component.type && props.component.type.startsWith('ew-');
});

// 为组件库组件准备适配的props
const adaptedProps = computed(() => {
  if (!props.component.props) return { datas: {} };
  return adaptPropsForLibraryComponent(props.component.props);
});

</script>

<style scoped>
.rendered-component {
  position: relative;
  box-sizing: border-box;
  cursor: move;
  transition: outline 0.1s ease-in-out, border-color 0.1s ease-in-out, border-style 0.1s ease-in-out;
  outline: none;
  display: flex;
  width: 100%;
  height: 100%;
}

/* 拖动手柄样式 */
.drag-handle {
  position: absolute;
  top: -18px;
  left: 0;
  height: 18px;
  width: 50px;
  background-color: #409eff;
  border-radius: 4px 4px 0 0;
  cursor: move;
  z-index: 100; /* 提高z-index确保手柄在最上层 */
  opacity: 0.9; /* 提高默认不透明度 */
  transition: opacity 0.2s, transform 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 0 4px rgba(0, 0, 0, 0.2);
}

.drag-handle:hover {
  opacity: 1;
  transform: scale(1.05);
  background-color: #66b1ff;
}

.drag-handle-text {
  color: white;
  font-size: 12px;
  font-weight: bold;
  pointer-events: none;
  text-shadow: 0 0 2px rgba(0, 0, 0, 0.3);
}

.drag-handle::before {
  content: "";
  position: absolute;
  left: 5px;
  top: 4px;
  width: 30px;
  height: 8px;
  background-image: linear-gradient(
    to right,
    white 1px,
    transparent 1px
  );
  background-size: 4px 100%;
  opacity: 0.6;
}

/* 确保内部组件填充整个容器空间 */
:deep(.el-card),
:deep(.el-button),
:deep(.el-input),
:deep(.el-select),
:deep(.el-date-picker),
:deep(.el-form),
:deep(.el-slider),
:deep(.el-color-picker),
:deep(.el-pagination),
:deep(.el-image),
:deep(.el-progress),
:deep(.el-switch) {
  width: 100%;
  height: 100%;
}

/* 未选中时的 hover 效果: 蓝色虚线边框 */
.rendered-component:hover:not(.selected):not(.drag-over-container) { 
   border: 1px dashed #a0cfff; 
}

/* 选中时的样式: 蓝色实线轮廓，无边框 */
.rendered-component.selected {
  outline: 1.5px solid #409eff !important; /* 使用 !important 确保覆盖 */
  outline-offset: 1px; 
  border: none !important; /* 选中时强制无边框 */
  cursor: default;
}

/* 未选中的容器指示边框: 灰色虚线 */
.rendered-component.container-indicator-border {
    border: 1px dashed #dcdfe6;
    /* 增加内边距，便于放置子组件 */
    padding: 5px;
    /* 最小尺寸，确保容器足够大以容纳子组件 */
    min-width: 100px;
    min-height: 60px;
}

/* 拖拽覆盖容器时的样式: 蓝色虚线边框 + 背景 */
/* 确保这条规则优先级高于 .container-indicator-border 和 hover */
.rendered-component.drag-over-container {
    background-color: rgba(64, 158, 255, 0.1);
    border: 2px dashed #409eff !important; /* 使用更粗的边框，更明显 */
    padding: 5px; /* 确保有足够的内部空间 */
}

/* 拖拽时的样式 */
.rendered-component.is-dragging-self {
  opacity: 0.8;
   cursor: grabbing;
}

.context-menu {
  position: fixed;
  background-color: white;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  z-index: 10000;
  padding: 5px 0;
  min-width: 100px;
}

.context-menu-item {
  padding: 8px 15px;
  font-size: 13px;
  color: #606266;
  cursor: pointer;
  white-space: nowrap;
}

.context-menu-item:hover {
  background-color: #ecf5ff;
  color: #409eff;
}

/* RadioGroup 和 CheckboxGroup 布局样式 */
:deep(.el-radio-group),
:deep(.el-checkbox-group) {
  display: flex; /* 启用弹性布局 */
  flex-wrap: wrap; /* 允许项目换行 */
  align-items: center; /* 垂直居中对齐项目 */
  gap: 10px 15px; /* 项目之间的垂直和水平间距 */
  width: 100%; 
  height: 100%; 
  box-sizing: border-box; /* 在宽高计算中包含内边距/边框 */
}

/* 确保单选/复选框项目在弹性布局中正确显示 */
:deep(.el-radio-group .el-radio),
:deep(.el-checkbox-group .el-checkbox) {
   /* 移除可能干扰间距的默认边距 */
   margin-right: 0 !important; 
   margin-left: 0 !important; 
   /* 防止项目收缩 */
   flex-shrink: 0; 
}

/* 库组件样式修正 */
:deep([class^="ew-"]) {
  width: 100%;
  height: 100%;
  display: flex;
}

/* 预览模式下组件样式 */
.rendered-component.preview-mode {
  cursor: default !important;
  outline: none !important;
  border: none !important;
}

/* 预览模式下禁用拖动手柄 */
.preview-mode .drag-handle {
  display: none !important;
}
</style> 